package com.dynamic.mybatis.core.builder;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dynamic.mybatis.core.metadata.DynamicMappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.apache.ibatis.session.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description
 * @Author xs
 * @Date 2021/11/10 15:48
 */
public class DynamicBaseMapperBuilder{
    protected Configuration configuration;
    private static String trimBlankRegex =  "^\\s*|\\s*$";
    private static String[] statementXmlTags = "<select|<select|<insert|<update|<delete|<parameterMap|<resultMap|<sql".split("\\|");

    public DynamicBaseMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    protected List<ResultMap> parserResultMap(String id, String resultType, String resultMap){
        List<ResultMap> resultMaps = new ArrayList<>();
        if(StringUtils.isNotBlank(resultType)){
            Class  resultTypeClass =  configuration.getTypeAliasRegistry().resolveAlias(resultType);
            ResultMap resultMapObj = new ResultMap.Builder(configuration,id + "-Inline",resultTypeClass, new ArrayList<>(),null).build();
            resultMaps.add(resultMapObj);
        }else if(StringUtils.isNotBlank(resultMap)){
            DynamicMapperAdapterBuilder dynamicXMLMapperBuilder = new DynamicMapperAdapterBuilder(configuration);
            XNode xNode  =  new XPathParser(resultMap).evalNode("/resultMap");
            id =  xNode.getStringAttribute("id");
            DynamicMappedStatement dms = new DynamicMappedStatement();
            dms.setId(id);
            dms.setMappedStatement(resultMap);
            dynamicXMLMapperBuilder.parser(dms);
            resultMaps.add(configuration.getResultMap(id));
        }
        return resultMaps;
    }


    protected String trimBlank(String str){
        if(str == null){
            return str;
        }
        Pattern pattern = Pattern.compile(trimBlankRegex);
        Matcher matcher = pattern.matcher(str);
        return  matcher.replaceAll("");
    }


    public static boolean isXml(String str) {
        for(String tag : statementXmlTags){
            if(str.startsWith(tag)){
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        String str = "<resultMap > select 1 </resultMap>";
        System.out.println(isXml(str));

        str = "123";
        System.out.println(isXml(str));
    }
}